package com.wyx.jdbc.utility;

import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author 王艺锡
 * @version 1.0
 * 这是一个工具类，用于连接Mysql和关闭资源
 */

public class JDBCUtils {
    private static String url;//url
    private static String user;//用户名
    private static String password;//密码
    private static String driver;//驱动名

    //在静态代码块中初始化
    static {

        try {
            Properties properties = new Properties();
            properties.load(new FileReader("src\\mysql.properties"));
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            //在实际开发中
            //将编译异常转成运行异常
            //调用者，可以选择捕获该异常，也可以是默认处理
            throw new RuntimeException(e);
        }

    }


    //静态方法，用于连接，返回connection对象
    public static Connection getConnection(){

        try {
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    //静态方法，用于关闭资源
    public static void close(ResultSet resultSet, Statement statement, Connection connection){

        //判断
        try {
            if(resultSet != null){
                resultSet.close();
            }
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
